package com.ceres.device.web.controller;

import com.ceres.device.pojo.OrderDevice;
import com.ceres.device.web.service.OrderDeviceService;
import com.ceres.entity.PageResult;
import com.ceres.entity.Result;
import com.ceres.entity.StatusCode;
import com.github.pagehelper.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderDeviceController {

    @Autowired
    private OrderDeviceService orderDeviceService;

    /**
     * 根据用户id查询用户订单
     *
     * @param cid
     * @return
     */
    @GetMapping("/findByCustomerId")
    public Result findByCustomerId(Integer cid) {
        try {
            List<OrderDevice> orderDeviceList = orderDeviceService.findByCustomerId(cid);
            return new Result(true, StatusCode.OK, orderDeviceList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }


    /**
     * 分页搜索实现
     * @param searchMap
     * @param pageNum
     * @param pageSize
     * @return
     */
    //农作物的分页查询功能
    @GetMapping("/findPage")
    public Result findPage(@RequestParam Map searchMap, String pageNum, String pageSize) {
        try {

            Integer page=1;
            Integer size=5;

            if (StringUtils.isNotEmpty(pageNum) && StringUtils.isNotEmpty(pageSize)){
                try {
                    page=Integer.parseInt(pageNum);
                    size=Integer.parseInt(pageSize);
                } catch (NumberFormatException e) {

                }
            }
            Page<OrderDevice> cropsList = orderDeviceService.findPage(searchMap,page,size);

            PageResult pageResult=new PageResult(cropsList.getTotal(),cropsList.getResult());

            return new Result(true,2000,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,2001);
        }
    }

    /**
     * 修改订单状态
     *
     * @param logoNum
     * @return
     */
    @PostMapping(value = "/update/{logoNum}")
    public Result updateOrder(Integer id, @PathVariable Integer logoNum) {
        try {
            //点击确认下单，从平台传一个标识符
            if (logoNum != null && logoNum == 1) {
                int count = orderDeviceService.updateOrder(id, logoNum);
                return new Result(true, StatusCode.OK, count);
            }
            throw new RuntimeException("请确认下单");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR);
        }
    }


    /**
     * 官方采购
     *
     * @param orderDevice
     * @return
     */
    @PostMapping(value = "/add")
    public Result addOrder(OrderDevice orderDevice) {
        orderDeviceService.add(orderDevice);
        return new Result(true, StatusCode.OK);
    }
}
